import random
import time
from datetime import datetime

from newpro.db import db
from newpro.util.comm import get_ali_object
from newpro.util.myredis import r
from newpro.views.base import BaseHandler


class GetPwd(BaseHandler): # 获取交易密码
    def get(self):
        userid = self.get_query_argument('userid')
        sql = "select pay_password from open_bank where userid = %d"%(int(userid))
        res = db.findOne(sql)
        return self.finish({'code':200,'pwd':res['pay_password']})
class Getuser(BaseHandler):
    def get(self):
        userid = self.get_query_argument('userid')
        sql = "select * from user where id=%d"%int(userid)
        res = db.findOne(sql)
        money = float(res['money'])
        # print(money)
        self.finish({'code':200,'data':money})


class Alipay(BaseHandler):
    def get(self):
        # 获取支付返回的参数
        userid = int(self.get_query_argument('userid'))
        money = str(self.get_query_argument('money'))
        number = datetime.strftime(datetime.now(), "%Y%m%d%H%M%S") + str(userid) + str(random.randint(100000, 999999))
        pwd = self.get_query_argument('pwd')
        sqlpwd = "select pay_password from open_bank where userid=%d" % userid
        res = db.findOne(sqlpwd)
        npwd = res['pay_password']
        if pwd != npwd:
            return self.finish({'code': 401, 'msg': '交易密码有误'})

        sql1 = "select money from user where id=%d" % userid
        res = db.findOne(sql1)
        # print(res)

        moneys = res['money']
        if moneys == None:
            sql = "update user set money='%s' where id=%d" % (money, userid)
        else:
            money = int(moneys) + int(money)
            sql = "update user set money='%s' where id=%d" % (money, userid)

        db.update(sql)
        static = 1
        # current_time = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
        sql2 = "insert into payrecord(number, userid, money, static) values ('%s',%d,'%s',%d)" % (
        number, userid, money, static)
        db.update(sql2)
        db.commit()
        pay = get_ali_object()
        query_params = pay.direct_pay(
            subject=str(userid) + "充值服务",  # 商品简单描述
            out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=float(money),  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        self.write({'code': 200, 'url': pay_url})
        # data = self.request.arguments
        # print(data)
        # # 对参数进行处理
        # data = {k: v[0].decode() for k, v in data.items()}
        # # 从字典中将sign删除
        # sign = data.pop('sign')
        # flag = pay.verify(data, sign)
        # if flag == True:
        #     print(1)
        # else:
        #     return self.finish({'code':400,'msg':'你犯法了'})


class Callback(BaseHandler):
    def get(self):
        data = self.request.arguments
        print(data)
        # 对参数进行处理
        data = {k: v[0].decode() for k, v in data.items()}
        # 从字典中将sign删除
        sign = data.pop("sign")
        # 获取支付宝对象
        alipay = get_ali_object()
        # 调用验签
        flag = alipay.verify(data, sign)
        print(flag)
        if flag == True:
            trade_no = self.get_query_argument('trade_no')
            out_trade_no = self.get_query_argument('out_trade_no')  # 订单号
            sql2 = "select * from payrecord where number='%s'" % (out_trade_no)
            res = db.findOne(sql2)
            userid = res['userid']
            money = res['money']

            try:
                sql = "update payrecord set static=2 where number='%s'" % (out_trade_no)
                db.update(sql)
                sql1 = "insert into money_order(userid, order_number, money) values (%d,'%s','%s')" % (
                userid, out_trade_no, money)
                db.update(sql1)
                db.commit()
            except:
                db.rollback()
            self.redirect("http://localhost:8080/balance")




def Paymentfailure():
    res = r.sortedset_getall("numberpay")
    if res:
        times = int(time.time()) - 1800
        # 获取这个区间的数据
        timess = r.sortedset_getbyscore("numberpay", 0, times)
        for i in timess:
            r.sortedset_delete("numberpay", i)
            print(i.decode())

            sql = "delete from payrecord where number='%s'"%(i.decode())
            db.add(sql)
            db.commit()
            print("*************")
    else:
        return "没有数据"


